#!/bin/bash

#
# delthumb -- by Dario Berzano <dario.berzano@gmail.com>
#
# Part of the lfscripts suite -- http://lfscripts.googecode.com/
#
# A script that uses exiftool to delete thumbnails from image files, JPEG files
# in particular
#

#
# External libraries
#

# Auto find executable path, following links if needed
export EXEC
export LIBPATH

function SetPaths() {
  local LINK=`readlink "$0"`
  if [ "$LINK" == "" ]; then
    # No symlink
    EXEC="$0"
  elif [ "${LINK:0:1}" == "/" ]; then
    # Absolute symlink
    EXEC="$LINK"
  else
    # Relative symlink
    EXEC=`dirname "$0"`/"$LINK"
  fi
  LIBPATH=`dirname "$EXEC"`
}

# Sets paths
SetPaths

# Loads libraries
source "$LIBPATH/libprogressbar"

#
# Global variables
#

# General purpose
export DRYRUN=0
export VERBOSE=0

#
# Functions
#

# Entry point
function Main() {

  local FILES

  if [ "$1" == "--all" ] || [ "$1" == "-a" ]; then
    FILES="*.jpg *.JPG *.jpeg *.JPEG"
  elif [ "$1" == "" ]; then
    echo "Specify a file name or --all"
    exit 1
  elif [ ! -r "$1" ]; then
    echo "Can't find $1"
    exit 2
  else
    FILES="$1"
  fi

  local CTOT=0
  local CDEL=0
  local CERR=0
  local CNTH=0
  ProgressStart "Removing thumbnails..."
  for F in $FILES
  do
    if [ ! -r "$F" ]; then
      continue
    fi
    let CTOT++
    exiftool -ThumbnailImage "$F"|grep "Thumbnail Image" > /dev/null 2>&1
    if [ $? == 0 ]; then
      # Thumbnail found: delete it
      exiftool -tagsFromFile "$F" -ThumbnailImage= -m "$F" > /dev/null 2>&1 && \
        rm -f "$F"_original
      if [ $? == 0 ]; then
        let CDEL++
      else
        let CERR++
      fi
    else
      let CNTH++
    fi
    ProgressStep
  done
  ProgressStop "scanned: $CTOT, deleted: $CDEL, failures: $CERR"
}

Main "$@"
